package com.atguigu.ggkt.activity.service.impl;

import com.atguigu.ggkt.activity.mapper.CouponInfoMapper;
import com.atguigu.ggkt.client.user.UserInfoFeignClient;
import com.atguigu.ggkt.model.activity.CouponInfo;
import com.atguigu.ggkt.model.activity.CouponUse;
import com.atguigu.ggkt.activity.mapper.CouponUseMapper;
import com.atguigu.ggkt.activity.service.CouponUseService;
import com.atguigu.ggkt.model.user.UserInfo;
import com.atguigu.ggkt.model.vod.Course;
import com.atguigu.ggkt.vo.activity.CouponInfoVo;
import com.atguigu.ggkt.vo.activity.CouponUseQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.*;

/**
 * <p>
 * 优惠券领用表 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2022-04-29
 */
@Service
public class CouponUseServiceImpl implements CouponUseService {

    @Resource
    CouponUseMapper couponUseMapper;

    @Autowired
    private CouponUseService couponUseService;

    @Autowired
    private UserInfoFeignClient userInfoFeignClient;

    @Autowired
    private CouponInfoMapper couponInfoMapper;

    //获取已经使用优惠券列表（条件查询分页）
    @Override
    public IPage<CouponUse> selectCouponUsePage(Page<CouponUse> pageParam,
                                                CouponUseQueryVo couponUseQueryVo) {
        //获取条件
        Long couponId = couponUseQueryVo.getCouponId();
        String couponStatus = couponUseQueryVo.getCouponStatus();
        String getTimeBegin = couponUseQueryVo.getGetTimeBegin();
        String getTimeEnd = couponUseQueryVo.getGetTimeEnd();
        //封装条件
        QueryWrapper<CouponUse> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(couponId)) {
            wrapper.eq("coupon_id",couponId);
        }
        if(!StringUtils.isEmpty(couponStatus)) {
            wrapper.eq("coupon_status",couponStatus);
        }
        if(!StringUtils.isEmpty(getTimeBegin)) {
            wrapper.ge("get_time",getTimeBegin);
        }
        if(!StringUtils.isEmpty(getTimeEnd)) {
            wrapper.le("get_time",getTimeEnd);
        }
        //调用方法条件分页查询
        IPage<CouponUse> pageModel = couponUseMapper.selectPage(pageParam, wrapper);
        List<CouponUse> couponUseList = pageModel.getRecords();
        //遍历
        couponUseList.stream().forEach(item->{
            this.getUserInfoById(item);
        });
        return pageModel;
    }

    //更新优惠券
    @Override
    public void updateCouponInfoUseStatus(Long couponUseId, String orderId) {
        CouponUse couponUse = new CouponUse();
        couponUse.setId(couponUseId);
        couponUse.setOrderId(orderId);
        couponUse.setCouponStatus("1");
        couponUse.setUsingTime(new Date());
        couponUseMapper.updateById(couponUse);
    }

    @Override
    public Map<String, Object> findPage(Page<CouponUse> pageParam, Long userId) {
        //判断条件值是否为空，封装
        QueryWrapper<CouponUse> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);

        //调用方法进行条件分页查询
        Page<CouponUse> pages = couponUseMapper.selectPage(pageParam, wrapper);
        System.out.println("s2 >>> /api/activity/couponInfo/use/"+pageParam.getCurrent()+"/"+pageParam.getSize());
        //获取分页数据
        long totalCount = pages.getTotal();//总记录数
        long totalPage = pages.getPages();//总页数
        long currentPage = pages.getCurrent();//当前页
        long size = pages.getSize();//每页记录数
        //每页数据集合
        List<CouponUse> records = pages.getRecords();

        //封装其他数据（获取讲师名称 和 课程分类名称）
        records.stream().forEach(item -> {
            this.getCouponInfo(item);
        });
        //map集合返回
        Map<String,Object> map = new HashMap<>();
        map.put("total",totalCount);
        map.put("pageCount",totalPage);
        map.put("records",records);
        return map;
    }

    private void getCouponInfo(CouponUse item) {
        CouponInfo couponInfo = couponInfoMapper.selectById(item.getCouponId());
        item.getParam().put("amount",couponInfo.getAmount());
        item.getParam().put("ruleDesc",couponInfo.getRuleDesc());
    }

    //根据用户id，通过远程调用得到用户信息
    private CouponUse getUserInfoById(CouponUse couponUse) {
        //获取用户id
        Long userId = couponUse.getUserId();
        if(!StringUtils.isEmpty(userId)) {
            //远程调用
            UserInfo userInfo = userInfoFeignClient.getById(userId);
            if(userInfo != null) {
                couponUse.getParam().put("nickName",userInfo.getNickName());
                couponUse.getParam().put("phone",userInfo.getPhone());
            }
        }
        return couponUse;
    }

    @Override
    public Map<String,Object> selectCouponUse(Page<CouponUse> pageParam, Long userId){
        //判断条件值是否为空，封装
        LocalDate now = LocalDate.now();
        QueryWrapper<CouponUse> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        wrapper.eq("coupon_status", 0);
        wrapper.gt("expire_time", now);
        List<CouponUse> couponUseList = couponUseMapper.selectList(wrapper);

        //封装其他数据（获取讲师名称 和 课程分类名称）
        couponUseList.stream().forEach(item -> {
            this.getCouponInfo(item);
        });
        List<CouponInfoVo> list = convertToCouponInfoVo(couponUseList);
        //map集合返回
        Map<String,Object> map = new HashMap<>();
        map.put("abledCouponsList",list);
        return map;
    }

    public List<CouponInfoVo> convertToCouponInfoVo(List<CouponUse> couponUseList) {
        List<CouponInfoVo> convertToCouponInfoVoList = new ArrayList<>();
        couponUseList.stream().forEach(item -> {
            CouponInfoVo couponInfoVo = new CouponInfoVo();
            couponInfoVo.setId(item.getCouponId());
            couponInfoVo.setCouponUseId(item.getId());
            couponInfoVo.setAvailable(1);
            couponInfoVo.setDescription((String)item.getParam().get("ruleDesc"));
            couponInfoVo.setEndAt(item.getExpireTime().getTime());
            couponInfoVo.setStartAt(item.getStartTime().getTime());
            couponInfoVo.setCondition("无使用门槛");
            couponInfoVo.setValue(String.valueOf(item.getParam().get("amount")));
            couponInfoVo.setValueDesc("元");
            convertToCouponInfoVoList.add(couponInfoVo);
        });
        return convertToCouponInfoVoList;
    }
}
